<template>
    <main class="main-page">
        <template v-if="showHeader">
            <section class="page-section mb-3">
                <div class="container-fluid">
                    <div class="grid justify-content-between align-items-center">
                        <div class="col">
                            <div class="text-2xl text-primary font-bold">
                                {{ $t('employerApplications') }}
                            </div>
                        </div>
                        <div class="col-12 md:col-3">
                            <span class="p-input-icon-left w-full">
                                <i class="pi pi-search" />
                                <InputText 
                                    :placeholder="$t('search')" 
                                    class="w-full" 
                                    :value="filters.search.value" 
                                    @input="debounce(() => { filters.search.value = $event.target.value })" 
                                />
                            </span>
                        </div>
                    </div>
                </div>
            </section>
        </template>
        <section class="page-section">
            <div class="container-fluid">
                <div class="grid">
                    <div class="col comp-grid">
                        <div class="flex align-items-center">
                            <filter-tags :controller="page.filterController" />
                        </div>
                        <div>
                            <div class="page-records">
                                <DataTable 
                                    :lazy="true" 
                                    :loading="loading" 
                                    v-model:selection="selectedItems"
                                    :value="records" 
                                    dataKey="application_id" 
                                    @sort="onSort($event)" 
                                    class="p-datatable-sm" 
                                    :stripedRows="true" 
                                    :showGridlines="false" 
                                    :rowHover="true" 
                                    responsiveLayout="stack"
                                >
                                    <Column selectionMode="multiple" headerStyle="width: 2rem" />
                                    <Column field="company_name" :header="$t('companyName')">
                                        <template #body="{ data }">
                                            <router-link :to="`/employerapplications/view/${data.application_id}`">
                                                {{ data.company_name }}
                                            </router-link>
                                        </template>
                                    </Column>
                                    <Column field="business_license" :header="$t('businessLicense')" />
                                    <Column field="contact_person" :header="$t('contactPerson')" />
                                    <Column field="contact_phone" :header="$t('contactPhone')" />
                                    <Column field="contact_email" :header="$t('contactEmail')" />
                                    <Column field="application_status" :header="$t('applicationStatus')">
                                        <template #body="{ data }">
                                            <Tag 
                                                :severity="getStatusSeverity(data.application_status)"
                                                :value="getStatusText(data.application_status)"
                                            />
                                        </template>
                                    </Column>
                                    <Column field="created_at" :header="$t('createdAt')">
                                        <template #body="{ data }">
                                            {{ formatDate(data.created_at) }}
                                        </template>
                                    </Column>
                                    <Column field="reviewer_name" :header="$t('reviewer')">
                                        <template #body="{ data }">
                                            {{ data.reviewer_name || '-' }}
                                        </template>
                                    </Column>
                                    <Column headerStyle="width: 2rem" headerClass="text-center">
                                        <template #body="{ data }">
                                            <div class="flex justify-content-end">
                                                <SplitButton 
                                                    dropdownIcon="pi pi-bars" 
                                                    class="p-button dropdown-only p-button-text p-button-plain" 
                                                    :model="getActionMenuModel(data)"
                                                >
                                                    <i></i>
                                                </SplitButton>
                                            </div>
                                        </template>
                                    </Column>
                                </DataTable>
                            </div>
                            <!-- Empty record -->
                            <template v-if="pageReady && !records.length">
                                <div class="p-3 my-3 text-500 text-lg font-medium text-center">
                                    {{ $t('noRecordFound') }}
                                </div>
                            </template>
                            <!-- pagination component-->
                            <template v-if="showFooter && pageReady">
                                <div class="grid justify-content-between align-items-center">
                                    <div class="flex gap-2 flex-grow-0">
                                        <template v-if="auth.canView('employerapplications')">
                                            <div v-if="selectedItems.length" class="m-2">
                                                <Button 
                                                    @click="deleteItem(selectedItems)" 
                                                    icon="pi pi-trash" 
                                                    class="p-button-danger" 
                                                    :title="$t('deleteSelected')" 
                                                />
                                            </div>
                                        </template>
                                    </div>
                                    <div v-if="paginate && totalPages > 1" class="flex-grow-1">
                                        <Paginator 
                                            class="paginator-flat my-3" 
                                            :first="recordsPosition - 1" 
                                            @page="(event)=>{pagination.page = event.page + 1}" 
                                            :rows="pagination.limit" 
                                            :totalRecords="totalRecords"
                                        >
                                            <template #start>
                                                <span class="px-2">
                                                    {{ $t('records') }} <b>{{ recordsPosition }} {{ $t('of') }} {{ totalRecords }}</b>
                                                </span>
                                            </template>
                                        </Paginator>
                                    </div>
                                </div>
                            </template>
                        </div>
                    </div>
                </div>
            </div>
        </section>

        <!-- 审核对话框 -->
        <Dialog 
            v-model:visible="showReviewDialog" 
            :header="$t('reviewApplication')" 
            :modal="true"
            class="p-fluid"
            :style="{width: '50vw'}"
        >
            <div class="field">
                <label>{{ $t('applicationStatus') }}</label>
                <Dropdown
                    v-model="reviewData.application_status"
                    :options="statusOptions"
                    optionLabel="label"
                    optionValue="value"
                    :placeholder="$t('selectStatus')"
                />
            </div>
            <div class="field">
                <label>{{ $t('reviewNotes') }}</label>
                <Textarea
                    v-model="reviewData.review_notes"
                    :rows="4"
                    :placeholder="$t('enterReviewNotes')"
                />
            </div>
            <template #footer>
                <Button 
                    :label="$t('cancel')" 
                    icon="pi pi-times" 
                    class="p-button-text" 
                    @click="showReviewDialog = false"
                />
                <Button 
                    :label="$t('submit')" 
                    icon="pi pi-check" 
                    class="p-button-primary" 
                    @click="submitReview"
                    :loading="reviewLoading"
                />
            </template>
        </Dialog>
    </main>
</template>

<script setup>
import { ref, toRefs, onMounted } from 'vue';
import { usePageStore } from 'src/store/page';
import { useApp } from 'src/composables/app.js';
import { useAuth } from 'src/composables/auth';
import { $t } from 'src/services/i18n';
import { useListPage } from 'src/composables/listpage.js';
import { ApiService } from 'src/services/api';

const props = defineProps({
    primaryKey: {
        type: String,
        default: 'application_id',
    },
    pageStoreKey: {
        type: String,
        default: 'EMPLOYER_APPLICATIONS',
    },
    pageName: {
        type: String,
        default: 'employerapplications',
    },
    routeName: {
        type: String,
        default: 'employerapplicationslist',
    },
    apiPath: {
        type: String,
        default: 'employerapplications/index',
    },
    autoLoad: {
        type: Boolean,
        default: true,
    },
    enableCache: {
        type: Boolean,
        default: false,
    },
    paginate: {
        type: Boolean,
        default: true,
    },
    showHeader: {
        type: Boolean,
        default: true,
    },
    showFooter: {
        type: Boolean,
        default: true,
    },
    showBreadcrumbs: {
        type: Boolean,
        default: true,
    },
    multiCheckbox: {
        type: Boolean,
        default: true,
    },
    page: {
        type: Number,
        default: 1,
    },
    limit: {
        type: Number,
        default: 10,
    },
    search: {
        type: String,
        default: '',
    },
    sortBy: {
        type: String,
        default: 'created_at',
    },
    sortType: {
        type: String,
        default: 'desc',
    }
});

const app = useApp();
const auth = useAuth();

const defaultStoreState = {
    filters: {
        search: {
            tag: "Search",
            value: '',
            valueType: 'single',
            options: [],
        }
    },
    pagination: {
        page: props.page,
        limit: props.limit,
        sortBy: props.sortBy,
        sortType: props.sortType
    },
    primaryKey: props.primaryKey,
    enableCache: props.enableCache
};

const store = usePageStore(props.pageStoreKey, defaultStoreState);
const page = useListPage({ store, props });

const { records, filters, totalRecords, selectedItems, pagination } = toRefs(store.state);
const { pageReady, loading } = toRefs(page.state);
const { pageBreadCrumb, totalPages, recordsPosition } = page.computedProps;
const { load, exportPage, debounce, onSort, deleteItem } = page.methods;

// 审核相关状态
const showReviewDialog = ref(false);
const reviewLoading = ref(false);
const currentApplication = ref(null);
const reviewData = ref({
    application_status: '',
    review_notes: ''
});

const statusOptions = [
    { label: '待审核', value: 'pending' },
    { label: '已通过', value: 'approved' },
    { label: '已拒绝', value: 'rejected' }
];

function getStatusSeverity(status) {
    const statusMap = {
        'pending': 'warning',
        'approved': 'success',
        'rejected': 'danger'
    };
    return statusMap[status] || 'info';
}

function getStatusText(status) {
    const statusMap = {
        'pending': '待审核',
        'approved': '已通过',
        'rejected': '已拒绝'
    };
    return statusMap[status] || status;
}

function formatDate(dateString) {
    if (!dateString) return '';
    const date = new Date(dateString);
    return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit'
    });
}

function getActionMenuModel(data) {
    return [
        {
            label: () => $t('view'),
            to: `/employerapplications/view/${data.application_id}`,
            icon: "pi pi-eye",
            visible: auth.canView('employerapplications/view')
        },
        {
            label: () => $t('review'),
            command: () => openReviewDialog(data),
            icon: "pi pi-check-circle",
            visible: auth.canView('employerapplications/edit') && data.application_status === 'pending'
        },
        {
            label: () => $t('delete'),
            command: () => deleteItem(data.application_id),
            icon: "pi pi-trash",
            visible: auth.canView('employerapplications/delete')
        }
    ];
}

function openReviewDialog(data) {
    currentApplication.value = data;
    reviewData.value = {
        application_status: data.application_status,
        review_notes: ''
    };
    showReviewDialog.value = true;
}

async function submitReview() {
    try {
        reviewLoading.value = true;
        const response = await ApiService.post(
            `employerapplications/edit/${currentApplication.value.application_id}`,
            reviewData.value
        );
        
        if (response.data.success) {
            app.flashMsg('审核成功', '申请状态已更新', 'success');
            showReviewDialog.value = false;
            load(); // 重新加载列表
        } else {
            app.flashMsg('审核失败', response.data.message || '请稍后重试', 'error');
        }
    } catch (error) {
        console.error('Review error:', error);
        app.flashMsg('审核失败', error.response?.data?.message || '请稍后重试', 'error');
    } finally {
        reviewLoading.value = false;
    }
}

onMounted(() => {
    const pageTitle = $t('employerApplications');
    app.setPageTitle(props.routeName, pageTitle);
});
</script>

<style lang="scss" scoped>
.p-datatable {
    .p-datatable-tbody > tr > td {
        padding: 0.5rem;
    }
}

.p-dialog {
    .field {
        margin-bottom: 1.5rem;
        
        label {
            display: block;
            margin-bottom: 0.5rem;
            font-weight: 500;
        }
    }
}
</style> 